package com.walle.eve.aspect;

import java.util.Arrays;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 
 * 用于记录API接口的入参出参日志
 * 
 * @author xudawei
 * @date 2017年11月10日 下午2:08:56
 */
@Aspect
@Component
public class WebLogAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Around("execution(public * com.walle.eve.web..*.*(..))")
	public Object recordWeblog(ProceedingJoinPoint pjp) throws Throwable {
		Long startTime = System.currentTimeMillis();
		String logId = UUID.randomUUID().toString().replace("-", "");
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		logger.info("REQUEST  : LOGID={} - {} - {} - CLASS_METHOD={} - ARGS={}", logId, request.getMethod(), request.getRequestURL().toString(),
				pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName(), Arrays.toString(pjp.getArgs()));

		Object result = pjp.proceed();

		// 处理完请求，返回内容
		logger.info("RESPONSE : LOGID={} - TIME={}ms - BODY={}", logId, System.currentTimeMillis() - startTime, result);
		return result;
	}
}
